package net.sashag.nadlandroid;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.googlecode.androidannotations.annotations.EReceiver;
import com.googlecode.androidannotations.annotations.SystemService;

@EReceiver
public class NewMessageReceiver extends BroadcastReceiver {

	@SystemService
	protected NotificationManager notificationManager;
	
	private static int notificationId; //Increasing, while the application is alive this will ensure we get fresh notifications
	
	@Override
	public void onReceive(Context context, Intent intent) {
		Message newMessage;
		try {
			JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
			newMessage = NadlandroidPushChatMessage.fromPushJson(json);
			newMessage.saveAsNewParseObject();
		} catch (JSONException e) {
			Log.w("NewMessageReceiver", "Exception parsing JSON: " + e.getMessage());
			return;
		}
		
		Notification notification = new Notification(
				R.drawable.newmessagenotification,
				"Nadlandroid message from " + newMessage.getSenderName(),
				newMessage.getSendTime().getTime());
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		Intent activityLaunch = new Intent(context, MessagesActivity_.class);
		activityLaunch.setFlags(activityLaunch.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent contentIntent = PendingIntent.getActivity(context, -1, activityLaunch, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(context,
				"From " + newMessage.getSenderName(),
				"Interested in your apartment. You can contact the user back via email or phone.",
				contentIntent);
		notificationManager.notify(++notificationId, notification);
	}

}
